package tab;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.win32.StdCallLibrary;
import org.come.socket.GameClient;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class Main {
    public static TabJFrame tabJFrame;

    /**
     * 如果你需要在IDEA内运行就把这个设位  true
     * 如果生成登录器输入 false
     */
    public static boolean debug = true;
    public static String dir = System.getProperty("user.dir");
    public static WinDef.HWND showHWND;
    public static WinDef.HWND ts = null;
    public static boolean exit = false;
    public static boolean addIng = false;
    public static int lastX = -1;
    public static int lastY = -1;
    public static String title = GameClient.BT;
    private static Main instance = null;
    public static Map<Integer, WinDef.HWND> hwnds = new HashMap<>();

    public static Main getInstance() {
        return instance;
    }

    public static void main(String[] args) throws Exception{
    	 try {
             String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
             UIManager.setLookAndFeel(lookAndFeel);
         }catch (Exception e){
          //   e.printStackTrace();
         }

        tabJFrame = new TabJFrame();
        tabJFrame.setVisible(true);
        tabJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        tabJFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
             	System.exit(0);
            }
        });
        tabJFrame.addWindowFocusListener(new WindowAdapter() {
            public void windowGainedFocus(WindowEvent e) {
                User32.INSTANCE.AttachThreadInput(
                        new WinDef.DWORD(User32.INSTANCE.GetWindowThreadProcessId(ts, null)),
                        new WinDef.DWORD(User32.INSTANCE.GetWindowThreadProcessId(showHWND, null)),
                        true);
                 }
        });
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            tabJFrame.games.forEach((k, p) -> p.destroy());
            exit = true;
        }));
        new Thread(() -> {
            while (!exit) {
                try {
                    for (Iterator<Map.Entry<Integer, Process>> iterator = tabJFrame.games.entrySet().iterator();
                         iterator.hasNext();
                    ) {
                        Map.Entry<Integer, Process> entry = iterator.next();
                        hwnds.put(entry.getKey(), null);
                        Process process = tabJFrame.games.get(entry.getKey());
                        if (!process.isAlive()) {
                            tabJFrame.removeGame(entry.getKey());
                            iterator.remove();
                        }
                    }
                    if (tabJFrame.getX() != lastX ||
                            tabJFrame.getY() != lastY) {
                        Process process = tabJFrame.games.get(tabJFrame.getShouId());
                        try {
                            process.getOutputStream().write((tabJFrame.getX() + ":" + tabJFrame.getY() + "\n").getBytes());
                            process.getOutputStream().flush();
                            lastY = tabJFrame.getY();
                            lastX = tabJFrame.getX();
                        } catch (Exception e) {
                           e.printStackTrace();
                        }
                    }
                    if (tabJFrame.games.size() <= 0) System.exit(0);
                    if (ts == null) ts = User32.INSTANCE.FindWindow("SunAwtFrame", title);
                    if (hwnds.containsValue(null)) {
                        hwnds.forEach((k, v) -> {
                            WinDef.HWND hWnd = User32.INSTANCE.FindWindow("SunAwtFrame", "大话西游Ⅱ经典版 $Revision: 2309011-"+ k);
                            if (hWnd != null) {
                                User32.INSTANCE.SetParent(hWnd, ts);
                                User32.INSTANCE.SetWindowPos(hWnd, null, 0, 0, 0, 0, 0x0004 | 0x0080 | 0x0001 | 0x0002);
                            }
                        });
                    }

                    User32.INSTANCE.EnumChildWindows(ts, (hWnd, arg1) -> {
                        byte[] windowText = new byte[512];
                        User32_2.INSTANCE.GetWindowTextA(hWnd, windowText, 512);
                        String title = Native.toString(windowText, "GBK");
                        if (title.equals("大话西游Ⅱ经典版 $Revision: 2309011-" + tabJFrame.getShouId())) {
                            if (!User32.INSTANCE.IsWindowVisible(hWnd)) {
                                showHWND = hWnd;
                                User32.INSTANCE.ShowWindow(hWnd, 9);
                            }
                            WinDef.RECT qqwin_rect = new WinDef.RECT();
                            User32.INSTANCE.GetWindowRect(hWnd, qqwin_rect);
                            int width = Math.max(qqwin_rect.right - qqwin_rect.left, 645);// 获取内嵌窗体的宽
                            int height = Math.max(qqwin_rect.bottom - qqwin_rect.top, 500);// 获取内嵌窗体的高
                            User32.INSTANCE.MoveWindow(hWnd, 0, 38, width, height, true);
                            tabJFrame.setSize(width, Math.min(height + 38, width)); // 修改此处可以改变外面tab的尺寸
                        } else {
                            if (User32.INSTANCE.IsWindowVisible(hWnd)) User32.INSTANCE.ShowWindow(hWnd, 0);
                        }
                        return true;
                    }, null);
                    Thread.sleep(100);
                } catch (InterruptedException | NullPointerException e) {
                 //   e.printStackTrace();
                }
            }
        }).start();
    }

    public interface User32_2 extends StdCallLibrary {
        User32_2 INSTANCE = (User32_2) Native.loadLibrary("user32", User32_2.class);
        boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
        int GetWindowTextA(WinDef.HWND hWnd, byte[] lpString, int nMaxCount);
    }

}
